package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisID;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Autowired
    private ISeckillVoucherService iSeckillVoucherService;
    @Autowired
    private RedisID redisID;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILL;

    static {
        SECKILL = new DefaultRedisScript<>();
        SECKILL.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL.setResultType(Long.class);
    }
    private BlockingQueue<VoucherOrder> orders=new ArrayBlockingQueue<>(1024*1024);
    private ExecutorService service= Executors.newSingleThreadExecutor();
    //线程任务
    private class Task implements Runnable{
        @Override
        public void run() {
            while (true){
                //获取队列订单信息
                try {
                    VoucherOrder voucherOrder = orders.take();
                    //创建订单
                    VoucherOrders(voucherOrder);
                } catch (Exception e) {
                    log.error("订单异常",e);
                }
            }
        }
    }

    private void VoucherOrders(VoucherOrder voucherOrder) {
        Long id = voucherOrder.getUserId();
        //解决不同服务器获取线程而无法限制一人一单
        //RedisLock redisLock = new RedisLock("order:" + id, stringRedisTemplate);
        RLock lock = redissonClient.getLock("lock:order:" + id);
        //创建锁
        boolean tryLock = lock.tryLock();
        if (!tryLock){
            log.error("error");
            return ;
        }
        try {
            proxy.addvoucher(voucherOrder);
        }  finally {
            lock.unlock();
        }
    }

    //在类启动时执行
    @PostConstruct
    private void init(){
        service.submit(new Task());
    }
    private IVoucherOrderService proxy;
    @Override
    public Result add(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        //执行lua脚本
        Long execute = stringRedisTemplate.execute(SECKILL, Collections.emptyList(), voucherId.toString(), userId.toString());
        //结果为0，回返错误信息
        int i = execute.intValue();
        if (i != 0) {
            return Result.fail(i == 1 ? "库存不足" : "不能重复下单");
        }

        Long order = redisID.ID("order");
        //创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        //写入数据
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setId(order);
        voucherOrder.setUserId(userId);
        //将信息存入阻塞队列
        orders.add(voucherOrder);
        //获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        return Result.ok(order);
    }

//    @Override
//    public Result add(Long voucherId) {
//        //查询优惠券信息
//        SeckillVoucher voucher = iSeckillVoucherService.getById(voucherId);
//        //判断是否开始
//        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
//            Result.fail("活动尚未开始");
//        }
//        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
//            Result.fail("活动已结束");
//        }
//        //判断库存
//        if (voucher.getStock()<1){
//            Result.fail("库存不足");
//        }
//        //用户id加锁
//        Long id = UserHolder.getUser().getId();
//        //解决不同服务器获取线程而无法限制一人一单
//        //RedisLock redisLock = new RedisLock("order:" + id, stringRedisTemplate);
//        RLock lock = redissonClient.getLock("lock:order" + id);
//        //创建锁
//        boolean tryLock = lock.tryLock();
//        if (!tryLock){
//            return Result.fail("一人限一单");
//        }
//        try {
//            //获取代理对象
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.addvoucher(voucherId);
//        }  finally {
//            lock.unlock();
//        }
//
//    }

    @Transactional
    public void addvoucher(VoucherOrder voucherOrder) {
        Long id = voucherOrder.getUserId();
        //一人一单
        Integer count = query().eq("user_id", id).eq("voucher_id", voucherOrder.getVoucherId()).count();
        if (count>0){
            log.error("error");
            return;
        }
        boolean update = iSeckillVoucherService.update()
                .setSql("stock=stock-1")
                .eq("voucher_id", voucherOrder.getVoucherId()).gt("stock",0)
                .update();
        if (!update){
            log.error("库存不足");
            return;
        }

        //写入数据库
        save(voucherOrder);
    }
}
